<template>
  <div class="flex-wrap">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="90px"
      >
        <el-form-item label="用户/手机：" prop="phone">
          <el-input
            v-model="queryParams.phone"
            placeholder="用户昵称/手机号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="注册时间：" prop="registerTime">
          <el-date-picker
            v-model="queryParams.registerTime"
            type="daterange"
            value-format="YYYY-MM-DD"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="最近登录：" prop="lastLoginTime">
          <el-date-picker
            v-model="queryParams.lastLoginTime"
            type="daterange"
            value-format="YYYY-MM-DD"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="会员身份：" prop="memberType">
          <el-select
            v-model="queryParams.memberType"
            placeholder="请选择"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="item in userVip.consts"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="当前状态：" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="item in online.consts"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <div class="header-buttons">
            <el-button
              type="primary"
              @click="handleBatchUnban"
              :disabled="!selectedUsers.length"
              >批量解封</el-button
            >
            <el-button
              type="danger"
              @click="handleBatchBan"
              :disabled="!selectedUsers.length"
              >批量封禁</el-button
            >
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="userList"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="用户昵称/手机" min-width="140">
          <template #default="{ row }">
            <div>{{ row.userName }}</div>
            <div>{{ row.phone }}</div>
          </template>
        </el-table-column>
        <el-table-column
          label="注册时间"
          prop="enrollTime"
          width="160"
          align="center"
        />
        <el-table-column
          label="会员身份"
          prop="memberType"
          width="120"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="getMemberTagType(row.memberType)">
              {{ getMemberLabel(row.memberType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="token数量"
          prop="tokenNum"
          width="100"
          align="center"
        />
        <el-table-column
          label="最近登录"
          prop="lastLoginTime"
          width="160"
          align="center"
        />
        <el-table-column
          label="当前状态"
          prop="status"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="设备型号"
          prop="deviceModel"
          width="120"
          align="center"
        />
        <el-table-column label="操作" width="200" align="center">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleDetail(row)"
              >查看</el-button
            >
            <el-button
              v-if="row.status !== 'banned'"
              link
              type="danger"
              @click="handleBan(row)"
              >封禁</el-button
            >
            <el-button
              v-if="row.status === 'banned'"
              link
              type="success"
              @click="handleUnban(row)"
              >解封</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Search, Refresh } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { getUserList, batchBanUsers, batchUnbanUsers } from '@/api/user';
import { useRouter } from 'vue-router';
import { useDictStore } from '@/store/dict';

const dictStore = useDictStore();
const { userVip, online } = dictStore;

const router = useRouter();

// 查询参数
const initValues = () => {
  return {
    pageNum: 1,
    pageSize: 10,
    phone: '',
    RegisterStartTime: '',
    RegisterEndTime: '',
    registerTime: [],
    LastLoginStartTime: '',
    LastLoginEndTime: '',
    lastLoginTime: [],
    status: '',
    MemberIdentity: '',
  };
};

let queryParams = reactive(initValues());

const loading = ref(false);
const userList = ref([]);
const total = ref(0);
const selectedUsers = ref([]);

// 标签类型映射函数
const getMemberTagType = (type) => {
  const map = {
    normal: 'info',
    vip: 'warning',
    svip: 'danger',
  };
  return map[type] || 'info';
};

const getStatusTagType = (status) => {
  const map = {
    on_line: 'success',
    off_line: 'info',
    banned: 'danger',
  };
  return map[status] || 'info';
};

// 获取标签文本
const getMemberLabel = (type) => {
  const member = userVip.consts.find((item) => item.value === type);
  return member ? member.label : '普通用户';
};

const getStatusLabel = (status) => {
  const statusItem = online.consts.find((item) => item.value === status);
  return statusItem ? statusItem.label : '未知';
};

// 查询用户列表
const getList = async () => {
  loading.value = true;
  // 处理日期范围
  const params = { ...queryParams };
  if (params.registerTime && params.registerTime.length === 2) {
    params.registerTimeStart = params.registerTime[0];
    params.registerTimeEnd = params.registerTime[1];
  }
  if (params.lastLoginTime && params.lastLoginTime.length === 2) {
    params.lastLoginTimeStart = params.lastLoginTime[0];
    params.lastLoginTimeEnd = params.lastLoginTime[1];
  }
  delete params.registerTime;
  delete params.lastLoginTime;
  getUserList(params)
    .then(({ data }) => {
      console.log(data);
      total.value = data.total;
      userList.value = data.list;
    })
    .finally(() => {
      loading.value = false;
    });
};
// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置查询
const resetQuery = () => {
  Object.assign(queryParams, initValues());
  handleQuery();
};

// 处理分页大小变更
const handleSizeChange = (size) => {
  queryParams.pageSize = size;
  getList();
};

// 处理页码变更
const handleCurrentChange = (page) => {
  queryParams.pageNum = page;
  getList();
};

// 处理表格选择变更
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection;
};

// 查看用户详情
const handleDetail = (row) => {
  // 实际项目中，可以跳转到详情页面或打开详情弹窗
  router.push({
    path: '/user/detail',
    query: { id: row.sessionId },
  });
};

// 封禁用户
const handleBan = async (row) => {
  batchBanUsers([row.sessionId])
    .then(({ data }) => {
      console.log(data);
      ElMessage.success('封禁成功');
      getList(); // 刷新列表
    })
    .catch((err) => {})
    .finally(() => {});
};

// 解封用户
const handleUnban = async (row) => {
  batchBanUsers([row.sessionId])
    .then(({ data }) => {
      console.log(data);
      ElMessage.success('解除成功');
      getList(); // 刷新列表
    })
    .catch((err) => {})
    .finally(() => {});
};

// 批量封禁
const handleBatchBan = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请至少选择一个用户');
    return;
  }
  const userIds = selectedUsers.value.map((user) => user.sessionId);
  batchBanUsers(userIds)
    .then(({ data }) => {
      console.log(data);
      ElMessage.success('批量封禁成功');
      getList(); // 刷新列表
    })
    .catch((err) => {})
    .finally(() => {});
};

// 批量解封
const handleBatchUnban = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请至少选择一个用户');
    return;
  }
  const userIds = selectedUsers.value.map((user) => user.sessionId);
  batchUnbanUsers(userIds)
    .then(({ data }) => {
      console.log(data);
      ElMessage.success('批量解禁成功');
      getList(); // 刷新列表
    })
    .catch((err) => {})
    .finally(() => {});
};

// 初始加载数据
onMounted(() => {
  getList();
});
</script>

<style lang="less" scoped>
.search-card,
.table-card {
  margin-bottom: 20px;

  .el-card__header {
    padding: 15px 20px;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-buttons {
    display: flex;
    gap: 10px;
  }
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.text-muted {
  font-size: 13px;
  color: #909399;
  margin-top: 5px;
}
</style>
